using System;
using System.Collections;
using System.Data.Objects;
using Magiq.Providers.Entities.Query;
using MirrorMirror;

namespace Magiq.Providers.Entities.Support
{
    public static class LinqToEntitiesExtensions
    {
        private const string ProxyNamespace = "System.Data.Entity.DynamicProxies";

        public static ObjectContext ObjectContext(this object self)
        {
            if (self.IsEntityFrameworkProxy())
                return self.Get<ObjectContext>("_entityWrapper.Context");

            if (self is ObjectQuery)
                return ((ObjectQuery) self).Context;

            if (self is IMagiqToEntitiesCollectionQueryable)
                return ((IMagiqToEntitiesCollectionQueryable) self).BaseQueryable.ObjectContext();

            return null;
        }

        public static bool IsEntityFrameworkProxy(this object self)
        {
            return self.GetType().Namespace == ProxyNamespace;
        }

        private static readonly Guid ObjectSetGUID = typeof(ObjectSet<>).GUID;


        public static bool IsObjectSet(this IEnumerable enumerable)
        {
            var type = enumerable.GetType();
            return type.IsGenericType && type.GetGenericTypeDefinition().GUID == ObjectSetGUID;
        }
    }
}